package cc.endsearch.servlet;

import cc.endsearch.po.TextMessage;
import cc.endsearch.util.CheckUtil;
import cc.endsearch.util.MessageUtil;
import org.dom4j.DocumentException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

public class WeixinServlet extends HttpServlet {
    /**
     *@Author xcl
     *@Date 2017/11/6 15:44
     *@Description
     * 开发者模式接入：现将传入的3个字符串排序，拼接成一个字符串
     * 使用sha1加密 判断是否与 signature相同
     * 如果相同 进行输出 echostr
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        System.out.println("test");
        String signature = req.getParameter("signature");
        String timestamp = req.getParameter("timestamp");
        String nonce = req.getParameter("nonce");
        String echostr	 = req.getParameter("echostr");
        PrintWriter out = resp.getWriter();
        if(CheckUtil.checkSignatrue(timestamp,nonce,signature)){
            out.print(echostr);
        }
//        String echostr = req.getParameter("echostr");
//        PrintWriter out = resp.getWriter();
//        out.print(echostr);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = resp.getWriter();
        try {
            //接受消息集合
            Map<String,String> map = MessageUtil.amlToMap(req);
            //发送方帐号
            String fromUserName = map.get("FromUserName");
            //开发者微信号
            String toUserName = map.get("ToUserName");
            String msgType = map.get("MsgType");
            String content = map.get("Content");

            String massage = null;
            //如果发送的内容是text
            if(msgType.equals("text")){
                //返回消息
                TextMessage textMessage = new TextMessage();
                textMessage.setFromUserName(toUserName);
                textMessage.setToUserName(fromUserName);
                textMessage.setMsgType("text");
                textMessage.setCreateTime(new Date().getTime());
                textMessage.setContent("你发送的是"+content);
                massage = MessageUtil.textMessageToXml(textMessage);
            }
            printWriter.print(massage);
        } catch (DocumentException e) {
            e.printStackTrace();
        }finally {
            printWriter.close();
        }

    }
}
